
#coding:utf-8

import get_mongo_con
import time
import material
import json
import pymongo
from bson import ObjectId
import read_jounel


#参数列表：
def new_note(arg):
    collection = get_mongo_con.get_collection("note_content")
    dic = {}
    dic['note_sort'] = arg['note_sort']
    dic['publish_person'] = {"stu_id":arg["stu_id"], "name":arg["name"]}
    dic['is_passed'] = -1
    dic['publish_time'] = time.strftime("%Y-%m-%d %H:%M:%S")
    dic['audit'] = ''
    #@TODO
    dic['note_topic'] = ""
    dic['title'] = arg['title']
    dic['note_material_sub_id'] = arg['material_sub_id']
    dic['note_initial_id'] = material.get_latest_material(arg['material_sub_id'])

    receivers = {}
    for item in json.loads(arg['people_list']):
        single_receiver = {
            "is_send":False,
            "read_time":[]
        }
        receivers[str(item)] = single_receiver

    dic['receiver'] = receivers

    obj_id = collection.insert(dic)
    read_jounel.new_journal_index(obj_id)
    return obj_id

def get_note_list(stu_id):
    collection = get_mongo_con.get_collection("note_content")
    condition = {"publish_person.stu_id":stu_id}
    '愚蠢的语言？api？'
    return collection.find(condition).sort([["publish_time", pymongo.ASCENDING]])

#@TODO 修改数组子元素
def new_page_view(stu_id,note_id):
    now_time = time.time()
    collection = get_mongo_con.get_collection("note_content")
    try:
        result = collection.update({"_id": ObjectId(note_id)},{"$push":{"receiver." + str(stu_id) + ".read_time" : str(now_time)}})
        return collection.find_one({"_id":ObjectId(note_id)}).get('note_material_sub_id')
    except:
        return -1


def get_material_id(note_id):
    collection = get_mongo_con.get_collection("note_content")
    result = collection.find_one({"_id":ObjectId(note_id)}).get('note_material_sub_id')
    return result

def set_note_send(note_id, stu_id):
    collection = get_mongo_con.get_collection("note_content")
    return collection.update({"$and":[{"_id": ObjectId(note_id)} ,{"receiver.$.stu_id":stu_id}]}, {"$set":{"receiver.$.is_send":True}})

# print new_page_view('121270026',"555373ef9dd4e4326c060330")


# print new_page_view()